package com.weirdor.bootmybatis.admin.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class IndexController {


    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "redirect:index.html";
    }

    @ResponseBody
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public Map<String,Object> upload(HttpServletRequest request, MultipartFile file) throws IOException {
        Map<String,Object> map=new HashMap<>();
        //如果文件不为空，写入上传路径
        if(!file.isEmpty()) {
            //上传文件路径
            String path = "/Users/weirdor/zhy/boot-mybatis/img";
            //上传文件名
            String filename = file.getOriginalFilename();
            //获取上传文件的后缀名
            String prefix=filename.substring(filename.lastIndexOf(".")+1);
            //通过uuid来设置文件名
            filename= UUID.randomUUID()+"."+prefix;
            File filepath = new File(path,filename);
            //判断路径是否存在，如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件当中
            file.transferTo(new File(path + File.separator + filename));
            map.put("code",0);
            map.put("src","/"+UUID.randomUUID()+"."+prefix);
        } else {
            map.put("code",1);
        }
        return  map;
    }

}
